//
//  RelationRecommendCell.swift
//  todaySwift
//
//  Created by ChokWah on 2018/4/12.
//  Copyright © 2018年 ChokWah. All rights reserved.
//

import UIKit
import IBAnimatable

class RelationRecommendCell: UICollectionViewCell, RegisterCellOrNib {
    // 加载 图标
    @IBOutlet weak var loadingImageView: UIImageView!
    // 关注按钮
    @IBOutlet weak var concernButton: AnimatableButton!
    // 推荐原因
    @IBOutlet weak var recommendReasonLabel: UILabel!
    // 用户名称
    @IBOutlet weak var nameLabel: UILabel!
    // v图标
    @IBOutlet weak var vImageView: UIImageView!
    // 头像
    @IBOutlet weak var avatarImageView: AnimatableImageView!
    
    private lazy var animation: CABasicAnimation = {
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        animation.fromValue = 0
        animation.toValue = 2 * Double.pi
        animation.duration = 1.5
        animation.autoreverses = false
        animation.repeatCount = MAXFLOAT
        return animation
    }()
    var userCard: UserCard? {
        didSet {
            nameLabel.text = userCard!.user.info.name
            avatarImageView.kf.setImage(with: URL(string: userCard!.user.info.avatar_url)!)
            vImageView.isHidden = (userCard!.user.info.user_auth_info.auth_info  == "") ? true : false
            recommendReasonLabel.text = userCard!.recommend_reason
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        concernButton.setTitle("关注", for: .normal)
        concernButton.setTitle("已关注", for: .selected)
        concernButton.theme_setTitleColor("colors.userDetailConcernButtonTextColor", forState: .normal)
        concernButton.theme_setTitleColor("colors.userDetailConcernButtonSelectedTextColor", forState: .selected)
    }
    
    @IBAction func concernButtonAction(_ sender: AnimatableButton) {
        
        loadingImageView.isHidden = false
        loadingImageView.layer.add(animation, forKey: nil)
        if sender.isSelected { // 已经关注，执行取消关注
            NetWorkTool.relationUnfollow(user_id: userCard!.user.info.user_id, completionHandler: { (_) in
                sender.isSelected = !sender.isSelected
                self.loadingImageView.layer.removeAllAnimations()
                self.loadingImageView.isHidden = true
                self.concernButton.borderWidth = 0
            })
        }else {                      // 未关注，执行关注事件
            NetWorkTool.relationFollow(user_id: userCard!.user.info.user_id, completionHandler: { (_) in
                sender.isSelected = !sender.isSelected
                self.loadingImageView.layer.removeAllAnimations()
                self.loadingImageView.isHidden = true
                self.concernButton.theme_backgroundColor = "colors.globalRedColor"
                self.concernButton.borderColor = .grayColor232()
                self.concernButton.borderWidth = 1
            })
        }
    }

}
